package jnpf.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.mapper.CostBudgetMapper;
import jnpf.base.service.CostBudgetService;
import jnpf.base.service.SuperServiceImpl;
import jnpf.base.util.ExcelImporter;
import jnpf.onlinedev.entity.CostBudget;
import jnpf.onlinedev.entity.CostBudgetDto;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

@Service
public class CostBudgetServiceImpl extends SuperServiceImpl<CostBudgetMapper, CostBudget> implements CostBudgetService {

    @Override
    public void importFile(MultipartFile file) throws IOException {
        // 创建临时文件
        Path tempFile = Files.createTempFile("uploaded-", file.getOriginalFilename());

        // 将文件传输到临时文件
        file.transferTo(tempFile.toFile());

        System.out.println("文件地址：" + tempFile.toAbsolutePath());
         List<CostBudget> serviceQuotationDtos = ExcelImporter.importExcel(tempFile.toAbsolutePath().toString(), CostBudget.class);
            this.saveBatch(serviceQuotationDtos);
    }

    @Override
    public void deleteData2() {
        // 删除所有数据
        this.getBaseMapper().delete(new UpdateWrapper<>());
    }

    public String CreateExcel(String filename  ) throws IOException {

        Long count = this.getBaseMapper().selectCount(new UpdateWrapper<>());
        //  每页导出10万条
        int pageSize=50000;
        String th="/www/wwwroot/jnpf-resources/DocumentFile/${file_name}.xlsx";
        String filePath = th.replace("${file_name}", filename);
        ExcelWriter excelWriter = EasyExcel.write(filePath, CostBudgetDto.class)
                .build();


        for (int i=0; i<(count/pageSize)+1;i++)
               {
                   Page<CostBudget> costBudgetPage = this.getBaseMapper().selectPage(new Page<>(i + 1, pageSize), null);
                   List<CostBudget> records = costBudgetPage.getRecords();

                   System.out.println("开始复制："+System.currentTimeMillis());
                   List<CostBudgetDto> dtos = BeanUtil.copyToList(records, CostBudgetDto.class);
                   System.out.println("结束复制："+System.currentTimeMillis());
                   WriteSheet writeSheet = EasyExcel.writerSheet(i,+(i+1)+"").head(CostBudgetDto.class).build();
                   excelWriter.write(dtos,writeSheet);

               }
        excelWriter.finish();

        return filePath;
    }
}
